﻿using System;
using System.Collections.Generic;
using GameFramework.Battle.Core;
using Gameplay.PVE.Utils;
using RootMotion.FinalIK;
using UnityEngine;
using Random = System.Random;

namespace Gameplay.PVE.Survivor
{
    public class LookAtComponent: MonoBehaviour
    {
        public Transform aimTransform;
        public Transform start;
        public Transform target;

        private bool hasStart;
        public bool useStartPoint;

        private void Awake()
        {
            hasStart = start != null;
            useStartPoint = hasStart;
        }

        [SerializeField]
        private bool isAiming;
        private void LateUpdate()
        {
            if (!isAiming)
            {
                return;
            }
            var originAngles = aimTransform.localEulerAngles;
            if (useStartPoint)
            {
                var angle = GetAngleBetweenCenterAndStart();
                aimTransform.localEulerAngles = new Vector3(originAngles.x - angle, originAngles.y, originAngles.z);
            }
            else
            {
                var originForward = transform.forward;
                var targetForward = target.position - aimTransform.position;
                targetForward.y = 0;
                var targetAngle = PveUtils.GetAngle(originForward, targetForward);
                aimTransform.localEulerAngles = new Vector3(originAngles.x - targetAngle, originAngles.y, originAngles.z);
            }
        }

        private float GetAngleBetweenCenterAndStart()
        {
            var targetPoint = target.position;
            targetPoint.y = 0;
            var centerPoint = aimTransform.position;
            centerPoint.y = 0;
            var startPoint = start.position;
            startPoint.y = 0;
            var startPointForward = start.forward;
            startPointForward.y = 0;
            var centerToTargetDistance = Vector3.Distance(centerPoint, targetPoint);
            var centerToStartDistance = Vector3.Distance(centerPoint, startPoint);
            var angle = Vector3.Angle(centerPoint - startPoint, targetPoint - startPoint);
            var cosAngle = Mathf.Cos(angle * Mathf.Deg2Rad);
            var a = centerToStartDistance;
            var c = centerToTargetDistance;
            var startToTargetDistance = a * cosAngle + Mathf.Sqrt(a * a * cosAngle * cosAngle - a * a + c * c);
            var targetPoint2 = startPoint + startPointForward.normalized * startToTargetDistance;
            return PveUtils.GetAngle(targetPoint2 - centerPoint, targetPoint - centerPoint);
        }

        public void StartAim(Transform target, bool useStartPoint = true)
        {
            this.target = target;
            isAiming = true;
            this.useStartPoint = useStartPoint && hasStart;
        }

        public void EndAim()
        {
            target = null;
            isAiming = false;
            useStartPoint = false;
        }
    }
}
